$(function () {

    var form = window.form_query;
    var now = moment().format("YYYY-MM-DD");
    var timeLimitStart = form.timeLimitStart.value;
    var timeLimitEnd = form.timeLimitEnd.value;
    var startDate = moment(now).subtract(30, 'days').startOf('day');
    var lastmonth = moment().subtract(1, 'months');

    
    var endDate = moment(now).endOf('day');
    if (timeLimitStart && timeLimitEnd) {
        startDate = moment(parseInt(timeLimitStart));
        endDate = moment(parseInt(timeLimitEnd));
    }
    if(!timeLimitStart){
        form.timeLimitStart.value = startDate.startOf('day').format("x");
    }
    if(!timeLimitEnd){
        form.timeLimitEnd.value = endDate.startOf('day').format("x");
    }

    $('#stats_data_start').daterangepicker({
		"singleDatePicker": true,
		"timePicker": false,
        "startDate": startDate,
		//"timePicker24Hour": true,
		//"timePickerSeconds": true,
		//"minDate":lastmonth,
		"maxDate": now,
		"autoApply": true,
		"parentEl": "200",
		locale: {
			format: 'YYYY-MM-DD',
			applyLabel: '确认',
		    cancelLabel: '取消',
		    weekLabel: 'W',
		    customRangeLabel: 'Custom Range',
		    daysOfWeek:["日","一","二","三","四","五","六"],
		    monthNames: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"]
		}
	}, function(start, end, label) {
        form.timeLimitStart.value = start.startOf('day').format("x");
		// $('#stats_data_start').val(start.startOf('day').format("x"));
	});
	//$('#stats_data_start').val("");//清空控件默认时间
	
	$('#stats_data_end').daterangepicker({
		"singleDatePicker": true,
		"timePicker": false,
        "startDate": endDate,
		//"timePicker24Hour": true,
		//"timePickerSeconds": true,
		"autoApply": true,
		//"minDate":lastmonth,
		"maxDate": now,
		"parentEl": "200",
		locale: {
			format: 'YYYY-MM-DD',
			applyLabel: '确认',
		    cancelLabel: '取消',
		    weekLabel: 'W',
		    customRangeLabel: 'Custom Range',
		    daysOfWeek:["日","一","二","三","四","五","六"],
		    monthNames: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"]
		}
	}, function(start, end, label) {
        form.timeLimitEnd.value = start.endOf('day').format("x");
		// $('#stats_data_end').val(start.startOf('day').format("x"));
	});
	//$('#stats_data_end').val("");//清空控件默认时间

    //获取产品列表
    $.get("/stastics/getProList", function (re) {
        var proList = re.data;
        var proOptions = "<option selected='selected' value=''> 全部产品 </option>";
        for (var i in proList) {
            var pro = proList[i];
            proOptions += "<option value='" + pro.id + "'>" + pro.name + "</option>";
        }
        $("#product_list").html(proOptions);

    });

	var xAxis=[],scanSeries=[],openSeries=[],newOpenSeries=[];

    datecount(null,1); //加载扫码量
    dataDetailList(1); //加载列表
	//初始化扫码量echarts
	var scanChart = echarts.init(document.getElementById("main"));
	var scanOption = {
		    title: {
		        text: '基础指标趋势分析'
		    },
		    color:["#0099FF","#D87A80","#F39C12"],
		    tooltip: {
		        trigger: 'axis'
		    },
		    legend: {
		        data:['扫码量']
		    },
		    grid: {
		        left: '3%',
		        right: '4%',
		        bottom: '3%',
		        containLabel: true
		    },
		    toolbox: {
		        feature: {
		            saveAsImage: {}
		        }
		    },
		    xAxis: {
		        type: 'category',
		        boundaryGap: false,
		        data: xAxis
		    },
		    yAxis: {
		        type: 'value'
		    },
		    series: [
		        {
		            name:'扫码量',
		            type:'line',		            
		            data:scanSeries
		        }
		    ]
		};
	
	//使用指定配置项和数据显示图表
    scanChart.setOption(scanOption);
	
	//初始化用户量echarts
	var userMyChart = echarts.init(document.getElementById("main1"));
	var userOption = {
		    title: {
		        text: ''
		    },
		    color:["#0099FF","#D87A80","#F39C12"],
		    tooltip: {
		        trigger: 'axis'
		    },
		    legend: {
		        data:['用户量']
		    },
		    grid: {
		        left: '3%',
		        right: '4%',
		        bottom: '3%',
		        containLabel: true
		    },
		    toolbox: {
		        feature: {
		            saveAsImage: {}
		        }
		    },
		    xAxis: {
		        type: 'category',
		        boundaryGap: false,
		        data: xAxis
		    },
		    yAxis: {
		        type: 'value'
		    },
		    series: [
		        {
		            name:'用户量',
		            type:'line',		            
		            data:openSeries
		        }
		    ]
		};
	
	//使用指定配置项和数据显示图表
    userMyChart.setOption(userOption);
	
	//初始化新增用户量echarts
	var newUserMyChart = echarts.init(document.getElementById("main2"));
	var newUserOption = {
		    title: {
		        text: ''
		    },
		    color:["#0099FF","#D87A80","#F39C12"],
		    tooltip: {
		        trigger: 'axis'
		    },
		    legend: {
		        data:['新增用户']
		    },
		    grid: {
		        left: '3%',
		        right: '4%',
		        bottom: '3%',
		        containLabel: true
		    },
		    toolbox: {
		        feature: {
		            saveAsImage: {}
		        }
		    },
		    xAxis: {
		        type: 'category',
		        boundaryGap: false,
		        data: xAxis
		    },
		    yAxis: {
		        type: 'value'
		    },
		    series: [
		        {
		            name:'新增用户',
		            type:'line',		            
		            data:newOpenSeries
		        }
		    ]
		};
	//使用指定配置项和数据显示图表
    newUserMyChart.setOption(newUserOption);
    //查询
    // $(".m_showjs").hide();
    $("#d_show").click(function(){
    	$(this).removeClass("btn-warning").attr("class","btn btn-primary");
    	$("#m_show").removeClass("btn-primary").attr("class","btn btn-warning");
    	var a = $("#hidden_type").val("1");
    	console.log(a);
    });

    $("#m_show").click(function(){
    	$(this).removeClass("btn-warning").attr("class","btn btn-primary");
    	$("#d_show").removeClass("btn-primary").attr("class","btn btn-warning");
    	var a = $("#hidden_type").val("2");
    	console.log(a);
    });
    $("#btn_search").click(function(){
    	var type = $("#hidden_type").val();
    	var productId = $("#product_list").val();
    	var startTime= $("#timeLimitStart").val();
    	var endTime =$("#timeLimitEnd").val();
    	var starts = $("#stats_data_start").val();
    	var ends = $("#stats_data_end").val();

    	if(type != 1 && type !=2){
    		bootbox.balert("请先选择按天/按月查询")
		}
    	starts = starts.replace(/-/g,"/"); 
    	ends = ends.replace(/-/g,"/"); 
    	var begin = Date.parse(starts); 
    	var end = Date.parse(ends); 
    	console.log("开始日期与结束日期相差"+Math.ceil((end-begin)/(24*60*60*1000))+"天");
    	var dd = Math.ceil((end-begin)/(24*60*60*1000));
    	console.log(dd);
    	if(type == 1){
            if(dd>=31){
                //alert("按天显示，相差时间不能大于31天");
                bootbox.balert("按天显示，相差时间不能大于31天");
                return;
            }

		}else if(type == 2){
            if(dd>366){
                //alert("按天显示，相差时间不能大于31天");
                bootbox.balert("按月显示，相差时间不能大于366天");
                return;
            }
        }

    	if(dd<0){
    		bootbox.balert("开始时间不能大于结束时间");
    	}

        datecount(productId,type,startTime,endTime);

    	if(type ==1){
            $(".d_showjs").removeClass("hidden");
            $(".m_showjs").addClass("hidden");
        }else{
            $(".d_showjs").addClass("hidden");
            $(".m_showjs").removeClass("hidden");
        }

        var nXAxis = { type: 'category', boundaryGap: false,  data: xAxis };

        var sSeries = [{ name:'扫码量', type:'line', data:scanSeries }];
        scanOption.xAxis = nXAxis;
        scanOption.series = sSeries;
        scanChart.setOption(scanOption, true);

        var oSeries =[{ name:'用户量',type:'line',data:openSeries}];
        userOption.xAxis = nXAxis;
        userOption.series = oSeries;
        userMyChart.setOption(userOption, true);


        var noSeries = [{ name:'新增用户',type:'line',data:newOpenSeries }];
        newUserOption.xAxis = nXAxis;
        newUserOption.series = noSeries;
        newUserMyChart.setOption(newUserOption, true);

        dataDetailList(1);
    });
	//数据导出
	$("[name='btn_export']").click(function () {

        var type = $("#hidden_type").val();
        var productId = $("#product_list").val();
        var startTime= $("#timeLimitStart").val();
        var endTime =$("#timeLimitEnd").val();
	    
	    //有数据时才能导出
	    if($("#resultTotal_hidden").val() != 0){
	    	bootbox.bconfirm("确定是否导出？", function (re) {
	            if (re) {
	            	 var url="/stastics/statsDateListExport?productId="+productId + "&type="+type+"&startTime="+startTime+"&endTime="+endTime;
	                 window.open(url);
	            }
	        });
	    }else{
	    	bootbox.balert("没有数据，无法导出!");
	    }
	});

    //获取扫码统计数据
    function datecount(productId,type,startTime,endTime) {
        // var productId = $("#product_list").val();
        // var type =2;
        $.ajax({
            type: "get",
            url: "/stastics/dateCount",
            cache:false,
            async:false,
            data:{productId:productId,type:type,timeStart:startTime,timeEnd:endTime},
            dataType: "json",
            success: function(re){
                var data = re.data;
                var dateCount= data.dateCount,newOpen=data.newOpen;
                var len = dateCount.length;
                if(len != newOpen.length){
                    bootbox.balert("数据出错，请重新请求 !");
                    return;
                }

                xAxis=[];
                scanSeries=[];
                openSeries=[];
                newOpenSeries=[]

                if(len>0){
                    for (var i in dateCount) {
                        var p = dateCount[i];
                        var n = newOpen[i];
                        if(type == 1){
                            xAxis.push(p.vdate1);
						}else{
                            xAxis.push(p.year + '/' +p.month);
						}

                        scanSeries.push(p.scanCount);
                        openSeries.push(p.psnCount);
                        newOpenSeries.push(n.scanpan);
                    }
                }

            }
        });
    }

	function dataDetailList(page){
        var type = $("#hidden_type").val();
        var productId = $("#product_list").val();
        var startTime= $("#timeLimitStart").val();
        var endTime =$("#timeLimitEnd").val();

        page = page || 1;
        var  url ="/stastics/getStatsDateList?productId=" + productId +"&type=" + type + "&timeStart=" +startTime +
            "&timeEnd="+endTime+ "&page=" +page;

        $.post(url, function (re) {
            var result = re.data, resultList=result.result;
            var str = "";
            for(var i=0; i<resultList.length; i++){
                var para = resultList[i];
                str += '<tr>';
                if(type == 1){
                    str +=  '<td>'+para.vdate1 +'</td>';
                }else{
                    str +=  '<td>'+para.year + "/" + para.month +'</td>';
                }

                str +=  '<td>'+ para.scanCount + '</td>'+
                '<td>'+ para.psnCount + '</td>' +
                '<td>'+ para.scanpan + '</td>' +
                '<td>'+ (para.scanCount/(para.psnCount == 0 ? 1: para.psnCount)).toFixed(2) + '</td>' +
                 '<td>'+ para.history_scan_total + '</td>' +
                '<td>'+ para.redCount + '</td>' +
                '<td>'+ para.entityCount + '</td>' +
                '</tr>';
            }
            $('#tbody_data').html(str);
            resetPage(result.pageTotal, page);
        });
	}
	//分页

    function resetPage(totalPage, currPage){
        var innerHTML = [];
        currPage = currPage || 1;
        innerHTML.push('<ul class="pagination pagination-sm no-margin">');
        if(currPage > 1){
            innerHTML.push('<li class="prev"><a href="javascript:;"><span>上一页</span></a></li><li><a href="javascript:;"><span>1</span></a></li>');
        }
        if(currPage - 4 > 1){
            innerHTML.push('<li class="bigPrev"><a href="javascript:;"><span>...</span></a></li>')
        }
        for(var i = currPage - 3; i < currPage; i++){
            if(i > 1){
                innerHTML.push('<li><a href="javascript:;"><span>',i,'</span></a></li>');
            }
        }
        innerHTML.push('<li class="active"><span>', currPage,'</span></li>')
        for(var i = currPage+1; i < currPage+3; i++){
            if(i < totalPage){
                innerHTML.push('<li><a href="javascript:;"><span>',i,'</span></a></li>');
            }
        }
        if(currPage < totalPage - 3){
            innerHTML.push('<li class="bigNext"><a href="javascript:;"><span>...</span></a></li>');
        }
        if(currPage < totalPage){
            innerHTML.push('<li><a href="javascript:;"><span>', totalPage,'</span></a></li>',
                '<li class="next"><a href="javascript:;"><span>下一页</span></a></li>');
        }
        innerHTML.push("</ul>")
        $("#page_model").data("total", totalPage).html(innerHTML.join(""));
    }

    $("#page_model").on("click", "li", function () {
        if($(this).hasClass("active")){
            return false;
        }
        var currPage = parseInt($("#page_model .active").text()),
            totalPage = $("#page_model").data("total");
        if($(this).hasClass("prev")){
            currPage--;
        } else if($(this).hasClass("next")){
            currPage++;
        } else if($(this).hasClass("bigPrev")){
            currPage -= 5;

            if(currPage < 1){
                currPage = 1;
            }
        } else if($(this).hasClass("bigNext")){
            currPage += 5;

            if(totalPage - currPage < 0){
                currPage = totalPage;
            }
        } else {
            currPage = parseInt($(this).text());
        }

        dataDetailList(currPage);
    })
});

//===================以下为公共方法============================

/**   
*转换long值为日期字符串   
* @param l long值   
* @param pattern 格式字符串,例如：yyyy-MM-dd hh:mm:ss   
* @return 符合要求的日期字符串   
*/    

function getFormatDateByLong(l, pattern) {  
    return getFormatDate(new Date(l), pattern);  
}
/**   
 *转换日期对象为日期字符串   
 * @param l long值   
 * @param pattern 格式字符串,例如：yyyy-MM-dd hh:mm:ss   
 * @return 符合要求的日期字符串   
 */    
 function getFormatDate(date, pattern) {  
     if (date == undefined) {  
         date = new Date();  
     }  
     if (pattern == undefined) {  
         pattern = "yyyy-MM-dd hh:mm:ss";  
     }  
     return date.format(pattern);  
 }
//扩展Date的format方法   
 Date.prototype.format = function (format) {  
     var o = {  
         "M+": this.getMonth() + 1,  
         "d+": this.getDate(),  
         "h+": this.getHours(),  
         "m+": this.getMinutes(),  
         "s+": this.getSeconds(),  
         "q+": Math.floor((this.getMonth() + 3) / 3),  
         "S": this.getMilliseconds()  
     }  
     if (/(y+)/.test(format)) {  
         format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));  
     }  
     for (var k in o) {  
         if (new RegExp("(" + k + ")").test(format)) {  
             format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));  
         }  
     }  
     return format;  
 } 